// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    name: 'Login',
    component: () => import('../views/Login.vue'), // 懒加载
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue'), // 懒加载
    meta: { requiresAuth: true },
  },
  {
    path: '/logs',
    name: 'Logs',
    component: () => import('../views/Logs.vue'), // 懒加载
    meta: { requiresAuth: true },
  },
  {
    path: '/borrow',
    name: 'Borrow',
    component: () => import('../views/Borrow.vue'), // 懒加载
    meta: { requiresAuth: true },
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('../views/Users.vue'), // 懒加载
    meta: { requiresAuth: true },
  },
  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'), // 创建一个 NotFound.vue 页面
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫，确保需要认证的页面只能由登录用户访问
router.beforeEach((to, from, next) => {
  const user = JSON.parse(localStorage.getItem('user'));
  if (to.meta.requiresAuth && !user) {
    next({ name: 'Login' });
  } else if (to.name === 'Login' && user) {
    // 如果已登录，防止访问登录页
    next({ name: 'Dashboard' });
  } else {
    next();
  }
});

export default router;
